package top.cardone.context.aspect;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.annotation.AnnotationUtils;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.context.annotation.Action;
import top.cardone.context.util.ActionUtils;
import top.cardone.core.util.func.Func2;

import java.util.Map;

/**
 * Created by Administrator on 2015/8/3.
 */
public class ActionAspect {
    /**
     * 设置属性
     *
     * @param joinPoint 切片点
     */
    public Object actionPoint(final ProceedingJoinPoint joinPoint) throws Throwable {
        final java.lang.reflect.Method method = ((org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature()).getMethod();

        Action action = AnnotationUtils.findAnnotation(method, Action.class);

        if (action == null || StringUtils.isBlank(action.beanId())) {
            return joinPoint.proceed();
        }

        if (!StringUtils.startsWith(action.beanId(), "point-")) {
            return joinPoint.proceed();
        }

        final Map<String, Object> configMap = ActionUtils.getMap(action);

        if (MapUtils.isEmpty(configMap)) {
            return joinPoint.proceed();
        }

        return ApplicationContextHolder.func(Func2.class, func -> func.func(joinPoint, configMap));

//        final Map<String, Object> contextMap = Maps.newHashMap();
//
//        try {
//            ApplicationContextHolder.action(Action3.class, action3 -> {
//                ApplicationContextHolder.action(TaskExecutor.class, taskExecutor -> {
//                    TaskUtils.decorateTaskWithErrorHandler(() -> action3.action(joinPoint, configMap, contextMap), null, true);
//                });
//            }, MapUtils.getString(configMap, "beforeBeanId"));
//
//            final Object returnData = joinPoint.proceed();
//
//            ApplicationContextHolder.action(Action4.class, action4 -> {
//                ApplicationContextHolder.action(TaskExecutor.class, taskExecutor -> {
//                    TaskUtils.decorateTaskWithErrorHandler(() -> action4.action(joinPoint, configMap, returnData, contextMap), null, true);
//                });
//            }, MapUtils.getString(configMap, "afterBeanId"));
//
//            return returnData;
//        } catch (final Exception e) {
//            ApplicationContextHolder.action(Action4.class, action4 -> {
//                ApplicationContextHolder.action(TaskExecutor.class, taskExecutor -> {
//                    TaskUtils.decorateTaskWithErrorHandler(() -> action4.action(joinPoint, configMap, e, contextMap), null, true);
//                });
//            }, MapUtils.getString(configMap, "errorBeanId"));
//
//            throw e;
//        }
    }
}
